s<template>
  <base-breadcrumb>
    <template>
      <a-card>
        <titleName title="基本信息"></titleName>
        <!-- <a-button type="primary" @click="onSubmit">基本信息保存</a-button> -->
        <a-form-model ref="ruleForm" :model="form" :rules="rules" :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }" :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }">
          <a-row :gutter="24">
            <a-col :md="16" :sm="16">
              <a-form-model-item label="所属单位" prop="project" :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }" :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }">
                <org-tree-select v-model="form.projectId"  :disabled="true"  isAutoSelectFirst checkStrictly @select="selectOrg"></org-tree-select>
              </a-form-model-item>
            </a-col>
            <!-- <a-col :md="8" :sm="8">
                            <a-form-model-item label="所属分公司" prop="branchComId">
                                <SelectSubCompany
                                    :isDefaultSelected="pageType == 'add'"
                                    disabled
                                    placeholder="请选择"
                                    v-model="form.branchComId"
                                ></SelectSubCompany>
                            </a-form-model-item>
                        </a-col>
                        <a-col :md="8" :sm="8">
                            <a-form-model-item label="所属项目" prop="projectId">
                                <SelectProject
                                    disabled
                                    :isDefaultSelected="pageType == 'add'"
                                    placeholder="请选择"
                                    v-model="form.projectId"
                                    :form="form"
                                    :isClear="id == ''"
                                    keyValue="branchComId"
                                    @change="getRecordListReq"
                                ></SelectProject>
                            </a-form-model-item>
                        </a-col> -->
            <a-col :md="8" :sm="8">
              <a-form-model-item label="月份" prop="month">
                <a-month-picker @change="(date, dateString) => getTime(date, dateString, 'form', 'month')" placeholder="请选择" v-model="form.month" :disabled="pageType == 'look'"></a-month-picker>
              </a-form-model-item>
            </a-col>
            <a-col :md="8" :sm="8">
              <a-form-model-item label="商务策划类型" :labelCol="{ lg: { span: 6 }, sm: { span: 5 } }" :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }" prop="planBookType">
                <a-select placeholder="请选择" disabled v-model="form.planBookType">
                  <a-select-option value="INIT">初版</a-select-option>
                  <a-select-option value="ADJUST">动态调整</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col span="8">
              <a-form-model-item label="填报人">
                <BaseInput v-model="form.creatorName" disabled />
              </a-form-model-item>
            </a-col>
            <a-col span="8">
              <a-form-model-item label="填报日期">
                <a-date-picker v-model="form.createTime" disabled />
              </a-form-model-item>
            </a-col>
            <a-col span="18" class="mb20">
              <a-form-model-item label=" " :colon="false">
                <a-table bordered ref="table" size="default" rowKey="key" :columns="columns1" :data-source="loadData1" :alert="true" :pagination="false">
                  <template v-for="col in ['projectNum', 'effectProjectNum', 'confirmProjectNum', 'projectConfirmRate']" :slot="col" slot-scope="text, record">
                    <div :key="col" class="form-item">
                      <template v-if="pageType !== 'look'">
                        <span v-if="col === 'projectConfirmRate'">{{ record[col] == undefined ? '无' : record[col] + '%' }}</span>

                        <BaseInputNumber v-else v-model="record[col]" @change="change1(record)" :precision="2" />
                      </template>
                      <template v-else>
                        {{ text }}
                      </template>
                    </div></template
                  >
                </a-table>

                <a-table bordered ref="table" size="default" rowKey="key" :columns="columns2" :data-source="loadData2" :alert="true" :pagination="false">
                  <template v-for="col in ['projectTotalAmount', 'needConfirmBenefits', 'confirmBenefits', 'benefitsConfirmRate']" :slot="col" slot-scope="text, record">
                    <div :key="col" class="form-item">
                      <template v-if="pageType !== 'look'">
                        <span v-if="col === 'benefitsConfirmRate'">{{ record[col] == undefined ? '无' : record[col] + '%' }}</span>
                        <BaseInputNumber v-else v-model="record[col]" @change="change2(record, col)" :precision="2" />
                      </template>
                      <template v-else>
                        {{ text }}
                      </template>
                    </div></template
                  ></a-table
                >
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col span="8">
              <a-form-model-item label="自施合同额(不含税)(元)" prop="sinceContractAmount">
                <BaseInputNumber :disabled="pageType == 'look'" @change="change2(loadData2[0])" :precision="2" v-model="form.sinceContractAmount" />
              </a-form-model-item>
            </a-col>
            <a-col span="8">
              <a-form-model-item label="总立项金额占比自施合同额">
                <BaseInput v-model="form.projectTotalAmountRate" disabled />
              </a-form-model-item>
            </a-col>
            <a-col span="8">
              <a-form-model-item label="截止目前项目实际产值(不含税)(元)">
                <BaseInput v-model="form.projectActOutPutValueSoFar" disabled />
              </a-form-model-item>
            </a-col>
            <a-col span="8">
              <a-form-model-item label="优化效益率（不含税)">
                <BaseInput v-model="form.optimizeBenefitsRate" disabled />
              </a-form-model-item>
            </a-col>
            <a-col v-if="pageType === 'look'" :md="24" :sm="24">
              <a-form-model-item label="附件：" :label-col="{ lg: { span: 3 }, sm: { span: 5 } }" :wrapper-col="{ lg: { span: 18 }, sm: { span: 17 } }">
                <file-link :file-list="form.fileInfoVOList" />
              </a-form-model-item>
            </a-col>
            <a-col :md="24" :sm="24" v-else>
              <a-form-model-item label="附件上传">
                <l-table v-if="isUpdate" @fileArrysData="fileArrysData" :uploadArrys="form.fileInfoVOList" businessCode="BM15"></l-table>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </a-card>
      <div v-if="pageType !== 'look'" class="tool-btns mb20 page-btn-right-top">
        <a-button :loading="loading.DELETE" v-if="id != '' && form.auditStatus == 'DRAFT'" type="danger" @click="deleteDraft">删除草稿</a-button>
        <a-button v-if="form.auditStatus == 'REJECTED'" type="primary" :loading="loading.REJECTED" @click="submitForm('REJECTED')">保存</a-button>
        <a-button v-else :loading="loading.DRAFT" class="ml20" type="primary" :disabled="disabled" @click="submitForm('DRAFT')">保存草稿</a-button>
        <a-button :loading="loading.SUBMITTED" class="ml20" type="primary" :disabled="disabled" @click="submitForm('SUBMITTED')">提交</a-button>
        <a-button class="ml20" type="primary" @click="closeForm">关闭</a-button>
      </div>
      <div v-else class="tool-btns mb20 page-btn-right-top">
        <BasePrintButton v-if="!isAudit" type="primary" :beforePrintFn="print" />
        <a-button class="ml20" type="primary" @click="closeForm">关闭</a-button>
      </div>
    </template>
    <selectApprover :businessId="businessId" :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>

<script>
import { recordRow, rewrite, detailed, eliminate, queryProjectInfo, print, getSinceContractAmount } from '@/api/businessAffairs/planBook'
import { recordList } from '@/api/businessAffairs/throwMark'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 分公司
import SelectSubcontractor from '@/components/Select/SelectSubcontractor' // 分公司
import { isAttachment } from '@/utils/util'
import moment from 'moment'
import { STable } from '@/components'
const columns1 = [
  {
    title: '总立项数',
    width: '25%',
    dataIndex: 'projectNum',
    scopedSlots: { customRender: 'projectNum' }
  },
  {
    title: '按阶段应实施项目数',
    width: '25%',
    dataIndex: 'effectProjectNum',
    scopedSlots: { customRender: 'effectProjectNum' }
  },
  {
    title: '已确认项数',
    width: '25%',
    dataIndex: 'confirmProjectNum',
    scopedSlots: { customRender: 'confirmProjectNum' }
  },
  {
    title: '项目数确认率',
    width: '25%',
    dataIndex: 'projectConfirmRate',
    scopedSlots: { customRender: 'projectConfirmRate' }
  }
]
const columns2 = [
  {
    title: '立项总金额(不含税)(元)',
    width: '25%',
    dataIndex: 'projectTotalAmount',
    scopedSlots: { customRender: 'projectTotalAmount' }
  },
  {
    title: '按阶段应确认效益(不含税)(元)',
    width: '25%',
    dataIndex: 'needConfirmBenefits',
    scopedSlots: { customRender: 'needConfirmBenefits' }
  },
  {
    title: '已确认效益(不含税)(元)',
    width: '25%',
    dataIndex: 'confirmBenefits',
    scopedSlots: { customRender: 'confirmBenefits' }
  },
  {
    title: '按阶段效益确认率',
    width: '25%',
    dataIndex: 'benefitsConfirmRate',
    scopedSlots: { customRender: 'benefitsConfirmRate' }
  }
]
export default {
  name: 'a' + Date.now(),
  components: {
    SelectSubCompany,
    SelectProject,
    SelectSubcontractor,
    STable
  },

  data() {
    this.columns1 = columns1
    this.columns2 = columns2
    return {
      loadData1: [
        {
          projectNum: undefined,
          effectProjectNum: undefined,
          confirmProjectNum: undefined,
          projectConfirmRate: undefined
        }
      ],
      loadData2: [
        {
          projectTotalAmount: undefined,
          needConfirmBenefits: undefined,
          confirmBenefits: undefined,
          benefitsConfirmRate: undefined
        }
      ],
      id: '',
      isUpdate: true,
      rules: {
        month: [{ required: true, message: '请选择', trigger: 'change' }],
        sinceContractAmount: [{ required: true, message: '请输入', trigger: 'change' }]
      },
      pageType: 'add',
      userInfo: JSON.parse(sessionStorage.getItem('ycloud-user_info')),
      loading: {
        DELETE: false,
        DRAFT: false,
        SUBMITTED: false,
        REJECTED: false
      },
      disabled: false,

      form: {
        createTime: moment().format('YYYY-MM-DD'),
        creatorName: JSON.parse(sessionStorage.getItem('ycloud-user_info')).name,
        optimizeBenefitsRate: '',
        sinceContractAmount: '',
        projectId:null,
      },
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
  props: {
    isAudit: {
      // 是否作为审批详情
      type: Boolean,
      default: false
    }
  },
  watch: {
    isAudit: {
      immediate: true,
      handler(val) {
        if (val) {
          this.$nextTick(() => {
            this.pageType = 'look'
          })
        }
      }
    }
  },
  async mounted() {
    this.id = this.$route.query.id || []
    this.pageType = this.$route.query.pageType || 'add'
    if (this.$route.query.id) {
      this.isUpdate = false
      detailed(this.$route.query.id).then((res) => {
        this.isUpdate = true
        this.form = { ...res.data }
        this.loadData1[0].projectNum = this.form.projectNum
        this.loadData1[0].effectProjectNum = this.form.effectProjectNum
        this.loadData1[0].confirmProjectNum = this.form.confirmProjectNum
        this.loadData1[0].projectConfirmRate = this.form.projectConfirmRate
        this.loadData2[0].projectTotalAmount = this.form.projectTotalAmount
        this.loadData2[0].needConfirmBenefits = this.form.needConfirmBenefits
        this.loadData2[0].confirmBenefits = this.form.confirmBenefits
        this.loadData2[0].benefitsConfirmRate = this.form.benefitsConfirmRate
        //查询项目是否已经有投标交底记录
        if (this.pageType != 'look') {
          this.getRecordListReq(this.form.projectId)
        }
      })
    } else {
      this.form.projectId = this.$userInfo().currentPost.projectId;
    }
    this.$route.meta.title = this.id == '' ? '项目商务策划书新增' : '项目商务策划书编辑'
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('comm_plan_book_audit')
  },

  methods: {
    //选择单位
    selectOrg(val) {
      if (val && val.length) {
        this.form.branchComId = val[val.length - 2].orgId;
        this.form.projectName = val[val.length - 1].projectName
        this.form.branchComName = val[val.length - 2].orgName
        this.getRecordListReq(this.form.projectId)
      }
    },
    //根据项目id获取 =>自施合同额(不含税)(元)
    getSinceContractAmount(id) {
      getSinceContractAmount({ id: id }).then((res) => {
        console.log(res.data.data)
        this.$nextTick(() => {
          this.form.sinceContractAmount = res.data.data
          console.log(this.form.sinceContractAmount)
        })
      })
    },
    print() {
      return print(this.id).then((res) => {
        console.log(res)
        return res.data.content
      })
    },
    change1(record) {
      if (record.confirmProjectNum && record.effectProjectNum) {
        record.projectConfirmRate = ((record.confirmProjectNum / record.effectProjectNum) * 100).toFixed(2)
      }
    },
    change2(record) {
      if (record.confirmBenefits && record.needConfirmBenefits) {
        record.benefitsConfirmRate = ((record.confirmBenefits / record.needConfirmBenefits) * 100).toFixed(2)
      }
      if (record.projectTotalAmount && this.form.sinceContractAmount) {
        this.form.projectTotalAmountRate = ((record.projectTotalAmount / this.form.sinceContractAmount) * 100).toFixed(2)
      }
      if (record.confirmBenefits && this.form.projectActOutPutValueSoFar) {
        this.$nextTick(() => {
          this.form.optimizeBenefitsRate = ((record.confirmBenefits / this.form.projectActOutPutValueSoFar) * 100).toFixed(2)
        })
      }
    },
    getQueryProjectInfo(id) {
      queryProjectInfo(id).then((res) => {
        this.$nextTick(() => {
          this.form.planBookType = res.data.planBookType
          this.form.projectActOutPutValueSoFar = res.data.projectActOutPutValueSoFar
          // this.form.sinceContractAmount = res.data.sinceContractAmount
        })
      })
    },
    getTime(date, dateString, type, name) {
      this[type][name] = dateString
    },
    fileArrysData(val) {
      this.form.fileInfoVOList = val
    },
    // 删除草稿
    deleteDraft() {
      let that = this
      that.$confirm({
        title: '温馨提示',
        content: '确定是否删除数据？',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          return eliminate({ id: that.id })
            .then((res) => {
              that.$message.success('删除成功！')
              that.closeForm()
            })
            .catch((res) => {
              that.$message.warning('删除失败！')
            })
        }
      })
    },
    getRecordListReq(id) {
      if (!this.$route.query.id) {
        this.getQueryProjectInfo(id)
        this.getSinceContractAmount(id)
      }
      if (this.pageType == 'look') {
        return
      }
      let params = {
        projectId: id,
        pageNo: 1,
        pageSize: 10
      }
      recordList(params).then((res) => {
        if (res.code == '200') {
          this.planningBooks = res.data
          this.showTip()
        }
      })
    },

    showTip() {
      if (this.planningBooks.length == 0) {
        this.$message.warning('该项目暂无投标交底记录')
        this.disabled = true
      } else {
        this.disabled = false
      }
    },
    tableValidate() {
      console.log(this.form)

      if (
        this.form.projectNum == undefined ||
        this.form.projectNum == null ||
        this.form.effectProjectNum == undefined ||
        this.form.effectProjectNum == null ||
        this.form.confirmProjectNum == undefined ||
        this.form.confirmProjectNum == null ||
        this.form.projectTotalAmount == undefined ||
        this.form.projectTotalAmount == null ||
        this.form.needConfirmBenefits == undefined ||
        this.form.needConfirmBenefits == null ||
        this.form.confirmBenefits == undefined ||
        this.form.confirmBenefits == null
      ) {
        this.$message.warning('请填写完整数据!')
        return true
      } else {
        return false
      }
    },
    submitForm(auditStatus) {
      this.setProcessConfig = null
      if (this.disabled) return
      this.form = { ...this.form, ...this.loadData1[0], ...this.loadData2[0] }
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (isAttachment(this, auditStatus, this.form.fileInfoVOList)) return
          if (this.tableValidate()) return
          this.loading[auditStatus] = true
          console.log(this.loading[auditStatus])
          this.form.auditStatus = auditStatus
          // delete this.form.project
          this.submitApprovalConfirm(auditStatus == 'SUBMITTED' && this.form.planBookType == 'INIT'?this.processConfig:6,(flag)=>{
            if(!flag) {
              this.loading[auditStatus] = false
              return
            }
          if (this.$route.query.id) {
            rewrite(this.form).then((res) => {
              this.loading[auditStatus] = false
              if (res.code === 200) {
                this.$message.success('成功')
                //商务策划类型为初版，才有流程
                if (auditStatus == 'SUBMITTED' && this.form.planBookType == 'INIT') {
                  //提交时，返回id
                  this.businessId = res.data.id || this.id
                  this.setProcessConfig = this.processConfig
                  return
                } else {
                  this.closeForm()
                }
              } else {
                this.$message.info('失败')
              }
            })
          } else {
            recordRow(this.form).then((res) => {
              this.loading[auditStatus] = false
              if (res.data?.code === 200 || res.code == 200) {
                this.$message.success('成功')
                if (auditStatus == 'SUBMITTED' && this.form.planBookType == 'INIT') {
                  //提交时，返回id
                  this.businessId = res.data.id || this.id;
                  this.setProcessConfig = this.processConfig
                  return
                } else {
                  this.closeForm()
                }
              } else {
                this.$message.info('失败')
              }
            })
          }
          })
        } else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
    },
    // 关闭表单
    closeForm() {
      if (this.isAudit) {
        window.close()
      } else {
        this.$multiTab.close(this.$route.fullpath)
      }
    }
  }
}
</script>

<style lang="less" scoped>
@deep: ~'>>>';
.tool-btns {
  display: flex;
  justify-content: flex-end;
  @{deep} .ant-btn + .ant-btn {
    margin-left: 12px;
  }
}
.ant-form {
  min-height: 200px;
}
/deep/ .form-item  {
  .ant-input:not([disabled]),
  .ant-select:not(.ant-select-disabled) .ant-select-selection,
  .ant-calendar-picker-input,
  .ant-input-number-input,
  .ant-cascader-picker {
    border-color: #e4ac0b;
    background-color: #fff9e8;
  }
  .benefitsConfirmRate {
    .ant-input-number {
      border-color: #d9d9d9 !important;
      background-color: #f5f5f5 !important;
    }
  }
}
</style>
